package com.LeeCode;

import java.util.*;

/**
 * 统计近似相等数对 II
 */

public class Code3267 {
    public static void main(String[] args) {

    }

    private static final int[] POW10 = {1, 10, 100, 1000, 10000, 100000, 1000000};

    public int countPairs(int[] nums) {
        Arrays.sort(nums);
        int ans = 0;
        Map<Integer, Integer> cnt = new HashMap<>();
        int[] a = new int[7];
        for (int x : nums) {
            Set<Integer> st = new HashSet<>();
            st.add(x); // 不交换
            int m = 0;
            for (int v = x; v > 0; v /= 10) {
                a[m++] = v % 10;
            }
            for (int i = 0; i < m; i++) {
                for (int j = i + 1; j < m; j++) {
                    if (a[i] == a[j]) { // 小优化
                        continue;
                    }
                    int y = x + (a[j] - a[i]) * (POW10[i] - POW10[j]);
                    st.add(y); // 交换一次
                    swap(a, i, j);
                    for (int p = i + 1; p < m; p++) {
                        for (int q = p + 1; q < m; q++) {
                            st.add(y + (a[q] - a[p]) * (POW10[p] - POW10[q])); // 交换两次
                        }
                    }
                    swap(a, i, j);
                }
            }
            for (int v : st) {
                ans += cnt.getOrDefault(v, 0);
            }
            cnt.merge(x, 1, Integer::sum);
        }
        return ans;
    }

    private void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}
